﻿package net.wangit.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CompressionUtil {

	private static final Log log = LogFactory
			.getLog(net.wangit.util.CompressionUtil.class);

	public CompressionUtil() {
	}

	public static String compress(String upzipStr) {
		if (Checker.isEmpty(upzipStr))
			return "";
		String c = "";
		try {
			ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(outBuffer);
			gzip.write(upzipStr.getBytes());
			gzip.close();
			c = new String(outBuffer.toByteArray(), "ISO-8859-1");
			outBuffer.reset();
		} catch (IOException ex) {
			log.error((new StringBuilder("compress - error:")).append(
					ex.getMessage()).toString(), ex);
		}
		return c;
	}

	public static String decompress(String zipStr) {
		if (Checker.isEmpty(zipStr))
			return "";
		String c = "";
		try {
			ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
			ByteArrayInputStream inBuffer = new ByteArrayInputStream(zipStr
					.getBytes("ISO8859_1"));
			GZIPInputStream gunzip = new GZIPInputStream(inBuffer);
			byte buffer[] = new byte[256];
			int n;
			while ((n = gunzip.read(buffer)) >= 0)
				outBuffer.write(buffer, 0, n);
			c = new String(outBuffer.toByteArray(), "ISO-8859-1");
		} catch (IOException ex) {
			log.error((new StringBuilder("compress - error:")).append(
					ex.getMessage()).toString(), ex);
		}
		return CodeUtil.ISO2GBK(c);
	}

}
